package dao

import (
	"context"
	"encoding/json"
	"pay/api/pay"
	"pay/internal/model"
	"pay/pkg/log"
)

func (d *Dao) ReloadBootConfig(ctx context.Context) (err error) {
	var (
		bootConfigs []*model.BootInit
		bootJson    json.RawMessage
	)
	log.FromContext(ctx).Infow("加载全局配置信息...开始")
	if err = d.TransContext(ctx).Model(&model.BootInit{}).Scan(&bootConfigs).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	bootMap := make(map[string]string)
	for _, bootConfig := range bootConfigs {
		bootMap[bootConfig.Key] = bootConfig.Val
	}
	if bootJson, err = json.Marshal(bootMap); err != nil {
		return
	}
	if err = json.Unmarshal(bootJson, model.BootInfo); err != nil {
		return
	}
	log.FromContext(ctx).Infow("加载全局配置信息...完成")
	return
}

func (d *Dao) GetGlobalConfig(ctx context.Context, sgId uint32) (config *model.GlobalConfig, err error) {
	config = &model.GlobalConfig{}
	if err = d.TransContext(ctx).Model(&model.GlobalConfig{}).Where(
		"sg_id = ?", sgId).Take(config).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	return
}

func (d *Dao) FindStoreConfigsByStoreIds(ctx context.Context, sgId uint32, storeIds []uint32,
	payType pay.PayType, bizType pay.BizType) (configs []*model.StoreConfig, err error) {
	if err = d.TransContext(ctx).Model(&model.StoreConfig{}).Where(
		"sg_id = ? AND p_store_id in ? AND biz_type = ? AND pay_type = ? AND status = ?",
		sgId, storeIds, uint8(bizType), uint8(payType), true).Scan(&configs).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	return
}

func (d *Dao) GetStoreConfigByStoreId(ctx context.Context, sgId uint32, storeId uint32,
	payType pay.PayType, bizType pay.BizType) (config *model.StoreConfig, err error) {
	config = &model.StoreConfig{}
	if err = d.TransContext(ctx).Model(&model.StoreConfig{}).Where(
		"sg_id = ? AND p_store_id = ? AND biz_type = ? AND pay_type = ? AND status = ?",
		sgId, storeId, uint8(bizType), uint8(payType), true).Take(config).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	return
}

func (d *Dao) GetStoreConfigByStoreIdWithStatus(ctx context.Context, sgId uint32, storeId uint32,
	payType pay.PayType, bizType pay.BizType) (config *model.StoreConfig, err error) {
	config = &model.StoreConfig{}
	if err = d.TransContext(ctx).Model(&model.StoreConfig{}).Where(
		"sg_id = ? AND p_store_id = ? AND biz_type = ? AND pay_type = ?",
		sgId, storeId, uint8(bizType), uint8(payType)).Take(config).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	return
}

func (d *Dao) FindStoreConfigsByAccountId(ctx context.Context, accountId, sgId, storeId uint32,
	payType pay.PayType) (configs []*model.StoreConfig, err error) {
	if err = d.TransContext(ctx).Model(&model.StoreConfig{}).Where(
		"sg_id = ? AND p_store_id = ? AND pay_type = ? AND status = ? AND account_id = ?",
		sgId, storeId, uint8(payType), true, accountId).Scan(&configs).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	return
}
